package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.agent.OrderTraceLogsRecord;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.*;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.model.agent.OrderTraceLogsRecordItems;
import com.zbkj.service.dao.OrderTraceLogsRecordItemsDao;
import com.zbkj.service.service.OrderTraceLogsRecordItemsService;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.OrderTraceLogsRecordService;
import com.zbkj.service.service.SystemAttachmentService;
import com.zbkj.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Caiyc
* @description OrderTraceLogsRecordItemsServiceImpl 接口实现
* @date 2025-08-04
*/
@Service
@Slf4j
public class OrderTraceLogsRecordItemsServiceImpl extends ServiceImpl<OrderTraceLogsRecordItemsDao, OrderTraceLogsRecordItems> implements OrderTraceLogsRecordItemsService {

    @Resource
    private OrderTraceLogsRecordItemsDao dao;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;

    @Override
    public Boolean create(OrderTraceLogsRecordItemsFrontSaveRequest request) {
        SystemAdmin systemAdmin = userService.getSystemAdminByMerchantEmployee();
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = new OrderTraceLogsRecordItems();
        BeanUtils.copyProperties(request, orderTraceLogsRecordItems, "id");
        orderTraceLogsRecordItems.setMerId(systemAdmin.getMerId());
        // 图片地址处理
        if (StrUtil.isNotBlank(request.getImageUrl())) {
            orderTraceLogsRecordItems.setImageUrl(systemAttachmentService.clearPrefix(request.getImageUrl()));
        }
        boolean save = save(orderTraceLogsRecordItems);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询订单溯源号段明细表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<OrderTraceLogsRecordItems>
     * @author Caiyc
     * @since 2025-08-04
     */
    @Override
    public PageInfo<OrderTraceLogsRecordItemsPageDataResponse> getList(OrderTraceLogsRecordItemsSearchRequest request, PageParamRequest pageParamRequest) {
        Page<OrderTraceLogsRecordItemsFrontPageDataResponse> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<OrderTraceLogsRecordItems> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getIsDel, false);
        lambdaQueryWrapper.orderByAsc(OrderTraceLogsRecordItems::getSortOrder);
        lambdaQueryWrapper.orderByDesc(OrderTraceLogsRecordItems::getCreateTime);
        List<OrderTraceLogsRecordItems> orderTraceLogsRecordItemss = dao.selectList(lambdaQueryWrapper);
        List<OrderTraceLogsRecordItemsPageDataResponse> orderTraceLogsRecordItemsResponses = new ArrayList<>();

        orderTraceLogsRecordItemss.stream().forEach(x->{
            OrderTraceLogsRecordItemsPageDataResponse orderTraceLogsRecordItemsResponse = new OrderTraceLogsRecordItemsPageDataResponse();
            BeanUtils.copyProperties(x, orderTraceLogsRecordItemsResponse);
            orderTraceLogsRecordItemsResponses.add(orderTraceLogsRecordItemsResponse);
        });
        return CommonPage.copyPageInfo(page, orderTraceLogsRecordItemsResponses);
    }

    /**
     * 分页查询订单溯源号段明细表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<OrderTraceLogsRecordItems>
     * @author Caiyc
     * @since 2025-08-04
     */
    @Override
    public PageInfo<OrderTraceLogsRecordItemsFrontPageDataResponse> getListH5(OrderTraceLogsRecordItemsFrontSearchRequest request, PageParamRequest pageParamRequest) {
        Page<OrderTraceLogsRecordItemsFrontPageDataResponse> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<OrderTraceLogsRecordItems> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getIsDel, false);
        lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getOrderNo, request.getOrderNo());
        if (ObjectUtil.isNotNull(request.getId()) && request.getId() > 0) {
            lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getId, request.getId());
        }
        lambdaQueryWrapper.orderByAsc(OrderTraceLogsRecordItems::getSortOrder);
        lambdaQueryWrapper.orderByDesc(OrderTraceLogsRecordItems::getCreateTime);
        List<OrderTraceLogsRecordItems> orderTraceLogsRecordItemss = dao.selectList(lambdaQueryWrapper);
        List<OrderTraceLogsRecordItemsFrontPageDataResponse> orderTraceLogsRecordItemsResponses = new ArrayList<>();

        orderTraceLogsRecordItemss.stream().forEach(x->{
            OrderTraceLogsRecordItemsFrontPageDataResponse orderTraceLogsRecordItemsResponse = new OrderTraceLogsRecordItemsFrontPageDataResponse();
            BeanUtils.copyProperties(x, orderTraceLogsRecordItemsResponse);
            orderTraceLogsRecordItemsResponses.add(orderTraceLogsRecordItemsResponse);
        });
        return CommonPage.copyPageInfo(page, orderTraceLogsRecordItemsResponses);
    }

    @Override
    public PageInfo<OrderTraceLogsRecordItemsFrontPageDataResponse> getListUserH5(OrderTraceLogsRecordItemsFrontSearchRequest request, PageParamRequest pageParamRequest) {
        Page<OrderTraceLogsRecordItemsFrontPageDataResponse> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<OrderTraceLogsRecordItems> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getIsDel, false);
        lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getOrderNo, request.getOrderNo());
        if (ObjectUtil.isNotNull(request.getId()) && request.getId() > 0) {
            lambdaQueryWrapper.eq(OrderTraceLogsRecordItems::getId, request.getId());
        }
        lambdaQueryWrapper.orderByAsc(OrderTraceLogsRecordItems::getSortOrder);
        lambdaQueryWrapper.orderByDesc(OrderTraceLogsRecordItems::getCreateTime);
        List<OrderTraceLogsRecordItems> orderTraceLogsRecordItemss = dao.selectList(lambdaQueryWrapper);
        List<OrderTraceLogsRecordItemsFrontPageDataResponse> orderTraceLogsRecordItemsResponses = new ArrayList<>();

        orderTraceLogsRecordItemss.stream().forEach(x->{
            OrderTraceLogsRecordItemsFrontPageDataResponse orderTraceLogsRecordItemsResponse = new OrderTraceLogsRecordItemsFrontPageDataResponse();
            BeanUtils.copyProperties(x, orderTraceLogsRecordItemsResponse);
            orderTraceLogsRecordItemsResponses.add(orderTraceLogsRecordItemsResponse);
        });
        return CommonPage.copyPageInfo(page, orderTraceLogsRecordItemsResponses);
    }

    /**
    * 修改订单溯源号段明细表
    * @param request
    * @return
    */
    @Override
    public boolean update(OrderTraceLogsRecordItemsFrontSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入ID");
        }
        getByIdException(request.getId());
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = new OrderTraceLogsRecordItems();
        BeanUtils.copyProperties(request, orderTraceLogsRecordItems);
        // 图片地址处理
        if (StrUtil.isNotBlank(request.getImageUrl())) {
            orderTraceLogsRecordItems.setImageUrl(systemAttachmentService.clearPrefix(request.getImageUrl()));
        }
        orderTraceLogsRecordItems.setUpdateTime(new Date());
        return updateById(orderTraceLogsRecordItems);
    }

    private OrderTraceLogsRecordItems getByIdException(Integer id) {
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = getById(id);
        if (ObjectUtil.isNull(orderTraceLogsRecordItems)) {
            throw new AppException("订单溯源号段明细表不存在");
        }
        if (orderTraceLogsRecordItems.getIsDel()) {
            throw new AppException("订单溯源号段明细表不存在");
        }
        return orderTraceLogsRecordItems;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
        LambdaUpdateWrapper<OrderTraceLogsRecordItems> luw = Wrappers.lambdaUpdate();
        luw.set(OrderTraceLogsRecordItems::getIsDel, true);
        luw.in(OrderTraceLogsRecordItems::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除订单溯源号段明细失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public OrderTraceLogsRecordItemsDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<OrderTraceLogsRecordItems> lqw = Wrappers.lambdaQuery();
        lqw.eq(OrderTraceLogsRecordItems::getIsDel, 0);
        lqw.eq(OrderTraceLogsRecordItems::getId, id);
        lqw.last("limit 1");
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = this.getOne(lqw);
        if (ObjectUtil.isNotNull(orderTraceLogsRecordItems)) {
            OrderTraceLogsRecordItemsDetailResponse response = new OrderTraceLogsRecordItemsDetailResponse();
            BeanUtils.copyProperties(orderTraceLogsRecordItems, response);
            return response;
        }
        return null;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public OrderTraceLogsRecordItemsDetailResponse getDetailsUserH5(Integer id) {
        LambdaQueryWrapper<OrderTraceLogsRecordItems> lqw = Wrappers.lambdaQuery();
        lqw.eq(OrderTraceLogsRecordItems::getIsDel, 0);
        lqw.eq(OrderTraceLogsRecordItems::getId, id);
        lqw.last("limit 1");
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = this.getOne(lqw);
        if (ObjectUtil.isNotNull(orderTraceLogsRecordItems)) {
            OrderTraceLogsRecordItemsDetailResponse response = new OrderTraceLogsRecordItemsDetailResponse();
            BeanUtils.copyProperties(orderTraceLogsRecordItems, response);
            return response;
        }
        return null;
    }

    @Override
    public AddressDetailResponse getCurAddress(String longitude, String latitude) {
        AddressDetailResponse orderTraceLogsRecordItems = new AddressDetailResponse();
        // 调用腾讯地图获取地址信息
        String json = HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude
                + "," + longitude + "&key=" + Constants.TENCENT_MAP_KEY);
//        log.info("调用腾讯地图获取地址信息 json = " + json);
        if (StrUtil.isNotBlank(json)) {
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (jsonObject.getInteger("status").equals(0)) {
                JSONObject result = jsonObject.getJSONObject("result");
                if (result != null) {
                    String address = result.getString("address");
                    orderTraceLogsRecordItems.setAddress(address);
                    JSONObject formattedAddresses = result.getJSONObject("formatted_addresses");
                    if (formattedAddresses != null) {
                        String rough = formattedAddresses.getString("rough");
                        orderTraceLogsRecordItems.setPlace(rough);
                        String details = formattedAddresses.getString("standard_address");
                        orderTraceLogsRecordItems.setDetails(details);
                    }
                }
            }
        }
        orderTraceLogsRecordItems.setDate(DateUtil.now());
        return orderTraceLogsRecordItems;
    }

    @Override
    public OrderTraceLogsRecordItemsExistsResponse checkExists(OrderTraceLogsRecordItemsExistsRequest request) {
        LambdaQueryWrapper<OrderTraceLogsRecordItems> lqw = Wrappers.lambdaQuery();
        lqw.select(OrderTraceLogsRecordItems::getId);
        lqw.eq(OrderTraceLogsRecordItems::getIsDel, 0);
        lqw.eq(OrderTraceLogsRecordItems::getOrderNo, request.getOrderNo());
        lqw.eq(OrderTraceLogsRecordItems::getOperation, request.getOperation());
        lqw.last("limit 1");
        OrderTraceLogsRecordItems orderTraceLogsRecordItems = this.getOne(lqw);
        if (ObjectUtil.isNotNull(orderTraceLogsRecordItems)) {
            OrderTraceLogsRecordItemsExistsResponse response = new OrderTraceLogsRecordItemsExistsResponse();
            response.setId(orderTraceLogsRecordItems.getId());
            return response;
        }
        return null;
    }

}

